//
//  SEGPropertyAppraisalListViewController.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2018/12/10.
//  Copyright © 2018 刘山. All rights reserved.
//

#import "SEGPropertyAppraisalListViewController.h"
#import "SEGPropertyAppraisalCollectionViewCell.h"
#import "SEGPropertyAppraisalCollectionReusableView.h"
#import "SEGExcellentStaffDetailViewController.h"
#import "SEGStaffDetailPresentationController.h"
#import <SEGViewModel/SEGExcellentStaffViewModel.h>

#define kPropertyAppraisalCellID @"SEGPropertyAppraisalCollectionViewCell"
#define kPropertyAppraisalHeaderID @"SEGPropertyAppraisalCollectionReusableView"

@interface SEGPropertyAppraisalListViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) BOOL isStaffList; // 是否是员工列表
@property (nonatomic, strong) SEGExcellentStaffViewModel *viewModel;

@end

@implementation SEGPropertyAppraisalListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithTitle:(NSString *)title isStaffList:(BOOL)isStaffList {
    self = [super init];
    if (self) {
        self.title = title;
        self.isStaffList = isStaffList;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if (!self.isStaffList) {
        WeakSelf;
        [self.collectionView addWindmillWithHeaderRefreshBlock:^{
            [weakSelf loadData:YES];
        } footerRefreshBlock:^{
             [weakSelf loadData:NO];
        }];
        self.collectionView.seg_footer.ignoredScrollViewContentInsetBottom = 15;
        [self.collectionView beginHeaderRefreshing];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStaffFavorState:) name:kExcellentStaffFaverStateUpdateNotification object:nil];
}

- (void)setupUI {
    self.collectionView = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(floor((LYScreenWidth()-18-30)/3.0), 152);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 9;
        if (!self.isStaffList) {
            layout.headerReferenceSize = CGSizeMake(LYScreenWidth(), 54);
        }
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[SEGPropertyAppraisalCollectionViewCell class] forCellWithReuseIdentifier:kPropertyAppraisalCellID];
        [collectionView registerClass:[SEGPropertyAppraisalCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kPropertyAppraisalHeaderID];
        collectionView.contentInset = UIEdgeInsetsMake(self.isStaffList ? 10 : 0, 15, 15, 15);
        collectionView.alwaysBounceVertical = YES;
        [self.view addSubview:collectionView];
        collectionView;
    });
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    self.collectionView.backgroundColor = kColor_W;
}

- (void)loadData:(BOOL)isRefresh {
    WeakSelf;
    [[self.viewModel refreshListRequestSignal:isRefresh] subscribeNext:^(id  _Nullable x) {
        [weakSelf.collectionView stopAnimatingWindmill];
        weakSelf.dataSource = x;
        [weakSelf.collectionView reloadData];
        if ([weakSelf.dataSource count] == 0) {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":weakSelf.collectionView}];
        } else {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":weakSelf.collectionView}];
        }
    } error:^(NSError * _Nullable error) {
        [weakSelf.collectionView stopAnimatingWindmill];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

- (void)updateStaffFavorState:(NSNotification *)notification {
    SEGExcellentStaffModel *favoredStaff = notification.object;
    if (!favoredStaff || ![favoredStaff isKindOfClass:[SEGExcellentStaffModel class]]) {
        return;
    }
    
    for (SEGPropertyAppraisalModel *activityModel in self.dataSource) {
        for (SEGExcellentStaffModel *staffModel in activityModel.empeeList) {
            if ([staffModel.excellentEmpeeId isEqualToString:favoredStaff.excellentEmpeeId]) {
                staffModel.likeStatus = favoredStaff.likeStatus;
                staffModel.likeNum = favoredStaff.likeNum;
                break;
            }
        }
    }
    
    [self.collectionView reloadData];
}

#pragma mark - <UICollectionViewDelegate, UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 只有一期数据就展示全部优秀员工
    NSArray *staffList = self.dataSource[section].empeeList;
    if (self.dataSource.count < 2) {
        return staffList.count;
    }
    return MIN(staffList.count, 3);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGPropertyAppraisalCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kPropertyAppraisalCellID forIndexPath:indexPath];
    [cell updateCellWithModel:self.dataSource[indexPath.section].empeeList[indexPath.row]];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (!self.isStaffList) {
        SEGPropertyAppraisalCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kPropertyAppraisalHeaderID forIndexPath:indexPath];
        NSString *headerTitle = self.dataSource[indexPath.section].activityName;
        WeakSelf;
        header.clickMoreBlock = ^{
            SEGPropertyAppraisalListViewController *staffListVC = [[SEGPropertyAppraisalListViewController alloc] initWithTitle:headerTitle isStaffList:YES];
            staffListVC.dataSource = @[weakSelf.dataSource[indexPath.section]];
            [weakSelf.navigationController pushViewController:staffListVC animated:YES];
        };
        [header updateUIWithTitle:headerTitle showMoreButton:self.dataSource.count > 1];
        return header;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGExcellentStaffDetailViewController *detailVC = [[SEGExcellentStaffDetailViewController alloc] init];
    detailVC.dataSource = self.dataSource[indexPath.section].empeeList;
    detailVC.selectIndex = indexPath.row;
    SEGStaffDetailPresentationController *presentVC = [[SEGStaffDetailPresentationController alloc] initWithPresentedViewController:detailVC presentingViewController:self];
    detailVC.transitioningDelegate = presentVC;
    // 这个已经重写了present样式 不能再使用 detailVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:detailVC animated:YES completion:nil];
}

#pragma mark - lazy load
- (NSArray<SEGPropertyAppraisalModel *> *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray new];
    }
    return _dataSource;
}

- (SEGExcellentStaffViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[SEGExcellentStaffViewModel alloc] init];
    }
    return _viewModel;
}

@end
